package com.gx.cn.hospitalmanage;


import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.gx.cn.hospitalmanage.Control.TwitterRestClient;
import com.gx.cn.hospitalmanage.MyFragmentOne.NetUtils;
import com.gx.cn.hospitalmanage.MyFragmentOne.User;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;




import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import cz.msebera.android.httpclient.Header;

/**
 * Created by JCQ on 2017/9/25.
 */

public class RegisterActivity extends AppCompatActivity {



    Button register_button,btn_djs;
    EditText etPhone;
    String name,password, phone, getcodes , setcodes ,numif;
    Handler mHandler;


    protected  void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        mHandler = new Handler();


        register_button=(Button)findViewById(R.id.register_button);


        //注册
        register_button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                EditText   edtxt_YZM= (EditText) findViewById(R.id.text_yanzhengma);
                setcodes= edtxt_YZM.getText().toString().trim();
                EditText edtxt_UserName=(EditText)findViewById(R.id.text_name);
                EditText edtxt_UserPassword=(EditText)findViewById(R.id.text_password);
                name=edtxt_UserName.getText().toString();
                password=edtxt_UserPassword.getText().toString();


                 if(setcodes.equals(null) || setcodes.equals("")){

                     Toast.makeText (getApplicationContext(),"请输入验证码", Toast.LENGTH_LONG ).show();

                 }else{

                     if(getcodes==null){

                         Toast.makeText (getApplicationContext(),"请获取验证码", Toast.LENGTH_LONG ).show();
                     }else{

                         if( getcodes.trim().equals(setcodes)){

                             if(name.equals(null) || name.equals("")){
                                 Toast.makeText (getApplicationContext(),"请输入用户名", Toast.LENGTH_LONG ).show();
                             }else if(password.equals(null) || password.equals("")){
                                 Toast.makeText (getApplicationContext(),"请输入密码", Toast.LENGTH_LONG ).show();
                             }else{

                             new Thread(){
                               @Override
                             public void run() {
                                 Looper.prepare();
                                   numif=  InsertUser(name,password,phone);
                                   if(numif.equals("ok")){
                                       Intent it=new Intent(RegisterActivity.this,RegisterSuccessActivity.class);
                                       it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                       //不会返回注册界面了
                                       startActivity(it);
                                   }else {
                                       Toast.makeText (getApplicationContext(),"注册失败", Toast.LENGTH_LONG ).show();
                                   }
                                    Looper.loop();
                                   }
                                }.start();


                             }


                         }else{
                             Toast.makeText (getApplicationContext(),"验证码错误", Toast.LENGTH_LONG ).show();
                         }
                     }

                 }

            }
        });



        btn_djs =(Button) findViewById(R.id.btn_getZHM);
        //new倒计时对象，总共的时间，每隔多少秒更新一次时间
        final MyCountDownTimer myCountDownTimer=new MyCountDownTimer(60000,1000);
        //给Button设置点击时间，触发倒计时
        btn_djs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etPhone=(EditText) findViewById(R.id.text_phone);

                phone = etPhone.getText().toString();

                if(phone==null && phone==""){
                    Toast.makeText (getApplicationContext(),"请输入手机号码", Toast.LENGTH_LONG ).show();
                }else{
                    if(phone.length()==11){

                        new Thread(){
                            @Override
                            public void run() {
                                Looper.prepare();
                                getcodes =  TwitterRestClientUsage(phone);
                                Looper.loop();
                            }

                        }.start();

                        //发送后防止用户再次发送短信请求
                       myCountDownTimer.start();

                    }else{
                        Toast.makeText (getApplicationContext(),"请输入准确的手机号码", Toast.LENGTH_LONG ).show();
                    }

                }

            }
        });

    }


    //复写倒计时
    private  class MyCountDownTimer extends CountDownTimer {

        public MyCountDownTimer(long millisInFutrue,long countDownInterval){
            super(millisInFutrue,countDownInterval);

        }

        //计时过程
        @Override
        public void onTick(long ls) {
            //防止计时过程重复点
            btn_djs.setBackgroundColor(Color.parseColor("#D6D6D6"));
            btn_djs.setClickable(false);
            btn_djs.setText("剩余"+ ls/1000+"s");
        }

        //计时完毕的方法
        @Override
        public void onFinish() {
            //重新给Button设置文字
            btn_djs.setBackgroundColor(Color.parseColor("#49BADE"));
            btn_djs.setText("重新获取验证码");
            //设置可点击
            btn_djs.setClickable(true);
        }
    }



    //json格式与服务端交互
    private String InsertUser(String uname,String upassword, String phoneNumber){

        String urlPath="http://192.168.43.43:8080/20170112/logins/insertUser.action";  //手机网络
//     String urlPath="http://192.168.3.138:8080/20170112/logins/insertUser.action";  //网线网络

        URL url;

        String num="";

        try {
            url=new URL(urlPath);
            JSONObject jsonObject=new JSONObject();

            jsonObject.put("iphone", phoneNumber );
            jsonObject.put("username",uname);
            jsonObject.put("userpassword",upassword);

            String content=String.valueOf(jsonObject);  //json串转string类型
            HttpURLConnection conn=(HttpURLConnection) url.openConnection(); //开启连接
            conn.setConnectTimeout(5000);

            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("ser-Agent", "Fiddler");
            conn.setRequestProperty("Content-Type","application/json");
            //写输出流，将要转的参数写入流里
            OutputStream os=conn.getOutputStream();
            os.write(content.getBytes()); //字符串写进二进流
            os.close();

            int code=conn.getResponseCode();
            if(code==200){
                //读取返回的json数据
                InputStream inputStream=conn.getInputStream();
                // 调用自己写的NetUtils() 将流转成string类型
                num = NetUtils.readString(inputStream);



            }else{
                Toast.makeText (getApplicationContext(),"数据提交失败", Toast.LENGTH_LONG ).show();

            }

        }catch (Exception e){

        }

        return  num;

    }

    public  String TwitterRestClientUsage(String phoneNum) {


       RequestParams params=new RequestParams("phone",phoneNum);
       TwitterRestClient.get("logins/getYanZhengMa.action", params, new AsyncHttpResponseHandler() {
           @Override
           public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {

                 String jsonData=new String(responseBody);
               getcodes =jsonData ;
               Toast.makeText (getApplicationContext(),"发送验证码成功", Toast.LENGTH_LONG ).show();

           }

           @Override
           public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
               Toast.makeText (getApplicationContext(),"数据提交失败", Toast.LENGTH_LONG ).show();
           }

       });

       return getcodes;
   }


}
